<template>
  <scroll-view
    :scroll-y="true"
    @scrolltolower="load"
    @scroll="scroll"
    @refresherrefresh="onRefresh"
    :refresher-enabled="refresherEnabled && scrollTop < 50"
    :refresher-triggered="refreshing"
    refresher-background="transparent"
    :lower-threshold="75"
    :refresher-threshold="75"
  >
    <slot></slot>
    <view class="h-40" v-if="loadMoreEnabled">
      <u-loadmore :status="status" :load-text="loadText" />
    </view>
  </scroll-view>
</template>
<script>
export default {
  name: "vScroll",
  props: {
    offset: {
      default: 300,
      required: false,
    },
    refresherEnabled: {
      default: true,
      required: false,
      type: Boolean,
    },
    loadMoreEnabled: {
      default: true,
      required: false,
      type: Boolean,
    },
  },
  data() {
    return {
      loading: false,
      refreshing: false,
      finished: false,
      scrollTop: 0,
      loadText: {
        loadmore: "轻轻上拉",
        loading: "努力加载中",
        nomore: "实在没有了",
      },
    };
  },
  computed: {
    status() {
      if (this.refreshing) {
        return "loading";
      }
      if (this.loading) {
        return "loading";
      }
      if (this.finished) {
        return "nomore";
      }
      return "loadmore";
    },
  },
  methods: {

    scroll(event) {
      this.scrollTop = event.detail.scrollTop;
    },
    resetData() {
      this.loading = true
      this.$emit("ref", (callObj) => {
        this.loading = false
        if (!callObj) return;
        if (this.isBoolean(callObj.finished)) {
          this.finished = callObj.finished;
        } else {
          this.finished = true;
        }
      });
    },
    onRefresh($ev) {
      // 触发刷新并暴露结束函数
      if (this.refreshing) return;
      this.refreshing = true;
      this.$emit("ref", (callObj) => {
        this.refreshing = false;
        if (!callObj) return;
        if (this.isBoolean(callObj.finished)) {
          this.finished = callObj.finished;
        } else {
          this.finished = true;
        }
      });
    },
    isBoolean(ev) {
      return typeof ev == "boolean";
    },
    load() {
      // 未开启  不执行函数
      if (!this.loadMoreEnabled) return;
      // 触发加载并暴露结束函数
      if (this.loading || this.finished) return;
      this.loading = true;
      this.$emit("load", (callObj) => {
        this.loading = false;
        if (!callObj) return;
        if (this.isBoolean(callObj.finished)) {
          this.finished = callObj.finished;
        } else if (this.isBoolean(callObj.error)) {
          this.finished = callObj.error;
        }
      });
    },
  },
  mounted() {
    this.load();
  },
};
</script>